﻿define(["./form/_zuForm.js"], function(form) {
    var $scope;
    var $q;
    var $location;

    var initVarible = function(scope, q, location) {
        $scope = scope;
        $q = q;
        $location = location;

        $scope.isSelectAllChecked = false; //全选按钮是否选中

        $scope.tableHead = [];
        $scope.tableData = [];
        $scope.loadTableColumnFilterData = [];
        $scope.nowSelectItem = -1; //当前被选中的表格对象

        $scope.nowPage = 1; //当前是第几页
        $scope.inputPage = angular.copy($scope.nowPage);
        $scope.$watch('nowPage', function(newValue, oldValue, scope) {
            $scope.inputPage = $scope.nowPage;
        });

        $scope.nowCount = 10; //每页显示多少条
        $scope.nowCountForInt = 10;
        $scope.maxCount = 0; //数据总条数
        $scope.nowPageGroup = 1; //当前是第几组分页按钮
        $scope.numberOfPageGroup = 5; //一组分页按钮最多有几个
        $scope.lastPageGroup; //分页按钮组最后一组
        $scope.maxPageNumber; //分页按钮最大值
        $scope.pageButtonArray = []; //分页按钮组

        $scope.sortHeadObject = {}; //排序对象:{predicate:名称,sortWay:排序方式(sort-asc,sort-desc)}

        $scope.getTableBodyUrl; //获取表体信息url（分页方式）
        $scope.getSingleDataUrl; //获取单条数据url
        $scope.deleteDatasUrl; //批量删除url
        $scope.saveSingleDataUrl; //保存新增的单条数据url
        $scope.deleteSingleDataUrl; //删除单条数据url
        $scope._zuTableName; //表格名称

        $scope.showRowOperationButton = true; //是否显示操作列

        $scope.lastProjectHasDone = undefined; //此变量用来使内部的多个异步逻辑强制同步,为promise对象
    }

    var initFunctions = function() {
        LoadDetailTable();
    }

    var defineTableName = function(name) {
        $scope._zuTableName = name;
    }

    var defineGetTableBodyUrl = function(url) {
        $scope.getTableBodyUrl = url;
    }

    var defineGetSingleDataUrl = function(url) {
        $scope.getSingleDataUrl = url;
    }

    var defineDeleteDatasUrl = function(url) {
        $scope.deleteDatasUrl = url;
    }

    var defineSaveSingleDataUrl = function(url) {
        $scope.saveSingleDataUrl = url;
    }

    var defineDeleteSingleDataUrl = function(url) {
        $scope.deleteSingleDataUrl = url;
    }

    //加载数据详情表格
    function LoadDetailTable() {
        loadTableBody();
    }

    //从服务端加载表格数据(分页方式)(初始化时调用)
    function loadTableBody() {
        var sortObject = {};
        sortObject['sort-way'] = $scope.sortHeadObject.sortWay;
        sortObject['predicate'] = $scope.sortHeadObject.predicate;

        var requestData = {
            paging: {
                rowCount: $scope.nowCountForInt,
                colSort: sortObject,
                currentPage: $scope.nowPage,
            },
        };

        var promise = myHttpHandler("GET", $scope.getTableBodyUrl, requestData);
        promise.then(function(data) {
            // console.log("body data="+angular.toJson(data));
            renderTableHead(data);
            renderTableBody(data);
            initPaginationButton();
            setScopeFunction();
        });
    }

    //分页按钮点击时加载数据
    function reloadTableBody() {
        var sortObject = {};
        sortObject['sort-way'] = $scope.sortHeadObject.sortWay;
        sortObject['predicate'] = $scope.sortHeadObject.predicate;

        var requestData = {
            paging: {
                rowCount: $scope.nowCountForInt,
                colSort: sortObject,
                currentPage: $scope.nowPage,
            },
        };

        var promise = myHttpHandler("GET", $scope.getTableBodyUrl, requestData);
        promise.then(function(data) {
            // console.log("body data="+angular.toJson(data));
            renderTableHead(data);
            renderTableBody(data);
            initPaginationButton();

            $scope.afterTableFreshOk();
        });
    }

    //渲染表体
    function renderTableBody(data) {
        var allData = data;
        data = angular.fromJson(data);
        data = data.data.body;

        for (var i = 0; i < data.length; i++) {
            data[i].checked = false;
            data[i].show = true;
        }

        $scope.tableData = data;
        $scope.nowPage = allData.paging.currentPage;
        calcNowPageGroup($scope.nowPage);
        $scope.maxCount = allData.paging.rowTotal;
        $scope.nowCountForInt = allData.paging.rowCount;
        $scope.nowCount = $scope.nowCountForInt.toString();
    }

    //渲染表头
    function renderTableHead(data) {
        var sortObject = data.paging.colSort;
        var data = data.data.head;
        data = angular.fromJson(data);
        //为每个表头增加show,sortWay属性
        for (var i = 0; i < data.length; i++) {
            $scope.tableHead[i] = data[i];
            $scope.tableHead[i].show = true;
            if (data[i]['column-name'] == sortObject['predicate']) {
                $scope.tableHead[i].sortWay = sortObject['sort-way'];
            } else {
                $scope.tableHead[i].sortWay = "";
            }
        }
    }

    function myHttpHandler(type, url, data) {
        var deferred = $q.defer();

        $.ajax({
            async: true,
            type: type,
            url: url,
            data: data,
            dataType: "json",
            error: function(responseData) {
                alert("获取失败!");
            },
            success: function(responseData) {
                deferred.resolve(responseData);
                // console.log("return data="+JSON.stringify(responseData));
            }
        });

        return deferred.promise;
    }

    //渲染分页按钮
    function renderPagination() {
        $scope.pageButtonArray = [];
        var count;
        if ($scope.nowPageGroup == $scope.lastPageGroup) {
            count = $scope.maxPageNumber - ($scope.lastPageGroup - 1) * $scope.numberOfPageGroup;
        } else if ($scope.maxPageNumber > 0) {
            count = $scope.numberOfPageGroup;
        }

        for (var i = 0; i < count; i++) {
            $scope.pageButtonArray[i] = {};
            var startIndex = ($scope.nowPageGroup - 1) * $scope.numberOfPageGroup + 1;
            $scope.pageButtonArray[i].number = startIndex + i;
            $scope.pageButtonArray[i].isCurrent = ((i + 1) == ($scope.nowPage % 5 == 0 ? 5 : $scope.nowPage % 5) ? "current" : "");
        }

    }
    //计算分页按钮总数
    function calcMaxPageNumber() {
        if ($scope.maxCount <= 0) {
            $scope.maxCount = 1;
        }
        var temp = $scope.maxCount % $scope.nowCountForInt;
        var count = $scope.maxCount / $scope.nowCountForInt;
        count = parseInt(count);
        count = temp == 0 ? count : (count + 1);
        $scope.maxPageNumber = count;
    }
    //计算最后一个分页按钮组
    function calcLastPageGroup() {
        var count = parseInt($scope.maxPageNumber / $scope.numberOfPageGroup);
        $scope.lastPageGroup = $scope.maxPageNumber % $scope.numberOfPageGroup == 0 ? count : count + 1;
    }
    //显示当前页
    function showCurrentPagination(currentPage) {
        var nowPageIndex = currentPage % 5 == 0 ? 4 : currentPage % 5 - 1;
        $scope.pageButtonArray[nowPageIndex].isCurrent = "current";
    }

    function initPaginationButton() {
        calcMaxPageNumber();
        calcLastPageGroup();
        renderPagination();
    }

    //创建过滤器
    function createFilter() {
        var dialog = $("#filterWindow").data('dialog');
        $scope.filterObject = {};
        dialog.open();
    }

    //重新计算当前按钮组
    function calcNowPageGroup(page) {
        var newPageGroup = Number(parseInt((page - 1) / 5) + 1);
        if (newPageGroup != $scope.nowPageGroup) {
            $scope.nowPageGroup = newPageGroup;
        }
    }

    function setScopeFunction() {
        $scope.afterTableFreshOk = function() {

        }

        $scope.beforePageButtonClick = function() {

        }
        $scope.afterPageButtonClick = function() {

            }
            //分页按钮点击事件
        $scope.pageButtonClickEvent = function(page) {
            $scope.beforePageButtonClick();

            if (typeof page == "number") {
                var number = page;
                page = {};
                page.number = number;
                page.isCurrent = "";
            }
            var previouIndex = $scope.nowPage % 5;
            previouIndex = previouIndex == 0 ? 4 : previouIndex - 1;
            if (previouIndex >= $scope.pageButtonArray.length) {
                page.number = 1;
            } else {
                $scope.pageButtonArray[previouIndex].isCurrent = "";
            }

            if (page == 'previou') {
                if (($scope.nowPage - 1) == 0) {
                    showCurrentPagination($scope.nowPage);
                    return;
                } else if (($scope.nowPage - 1) % 5 == 0) {
                    $scope.nowPage--;
                    $scope.nowPageGroup--;
                    renderPagination();
                } else {
                    $scope.nowPage = $scope.nowPage - 1;
                    showCurrentPagination($scope.nowPage);
                }
            } else if (page == 'first') {
                $scope.nowPage = 1;
                $scope.nowPageGroup = 1;
                renderPagination();
            } else if (page == 'next') {
                if ($scope.nowPage % 5 == 0) {
                    if ($scope.nowPage >= $scope.maxPageNumber) {
                        showCurrentPagination($scope.nowPage);
                        return;
                    } else {
                        $scope.nowPage++;
                        $scope.nowPageGroup++;
                        renderPagination();
                    }
                } else {
                    if ($scope.nowPage >= $scope.maxPageNumber) {
                        showCurrentPagination($scope.nowPage);
                        return;
                    } else {
                        $scope.nowPage++;
                        showCurrentPagination($scope.nowPage);
                    }
                }
            } else if (page == 'last') {
                $scope.nowPage = $scope.maxPageNumber;
                var count = parseInt($scope.maxPageNumber / $scope.numberOfPageGroup);
                $scope.nowPageGroup = $scope.maxPageNumber % $scope.numberOfPageGroup == 0 ? count : count + 1;
                renderPagination();
            } else if (page.number > 0) {
                $scope.nowPage = page.number;
                calcNowPageGroup(page.number);
                renderPagination();
                showCurrentPagination($scope.nowPage);
            }

            //从服务器请求数据
            // loadTableBody();
            reloadTableBody();

            $scope.afterPageButtonClick();
        }

        //每页显示数据select事件
        $scope.nowCountSelectEvent = function() {
            $scope.nowCountForInt = parseInt($scope.nowCount);
            $scope.tableRefreshButtonClickEvent();
            // initPaginationButton();
        }

        //表格条目编辑按钮点击事件
        $scope.operationUpdateClickEvent = function(data) {
                form.initVariable($scope, $q);
                form.defineGetFormDataUrl($scope.getSingleDataUrl);
                form.defineSaveFormDataUrl($scope.saveSingleDataUrl);
                form.initFunctions();
                form.initForm(data, "edit");
            }
            //表格条目删除按钮点击事件
        $scope.operationDeleteClickEvent = function(data) {
                if (!confirm("确认删除?")) {
                    return;
                }
                var datas = $scope.tableData;
                for (var i = 0; i < datas.length; i++) {
                    if (datas[i].id == data.id) {
                        datas.splice(i, 1);
                        break;
                    }
                }

                var ids = [];
                ids.push(data.rowId);
                //提交服务器删除的id
                var promise = myHttpHandler("DELETE", $scope.deleteSingleDataUrl + data.rowId, {});
                promise.then(function(data) {
                    // alert(angular.toJson(data));
                });
                //刷新表格
            }
            //编辑窗口关闭按钮点击事件
        $scope.updateWindowCloseButtonClickEvent = function() {
                var dialog = $("#updateWindow").data('dialog');
                dialog.close();
            }
            //编辑窗口保存按钮点击事件
        $scope.updateWindowSaveButtonClickEvent = function() {
            //上传修改的数据到服务器
            // $scope.updateObject=$scope.formData;
            alert("update object=" + angular.toJson($scope.updateObject));
            var rowId = $scope.updateObject.rowId;
            var promise = myHttpHandler("PUT", $scope.saveSingleDataUrl + rowId, { record: angular.toJson($scope.updateObject) });
            promise.then(function(data) {
                var dialog = $("#updateWindow").data('dialog');
                dialog.close();
                $scope.tableRefreshButtonClickEvent();
            });
            // alert(angular.toJson($scope.updateObject));

            // var dialog = $("#updateWindow").data('dialog');
            // dialog.close(); 
        }

        //表格全选按钮点击事件
        $scope.selectAllCheckBoxEvent = function() {
            var datas = $scope.tableData;
            for (var i = 0; i < datas.length; i++) {
                if ($scope.isSelectAllChecked) {
                    datas[i].checked = true;
                } else {
                    datas[i].checked = false;
                }
            }
        }

        //表格列属性点击事件（排序）
        $scope.sortHeadClickEvent = function(head) {
            if ($scope.sortHeadObject['column-name'] != head['column-name']) {
                $scope.sortHeadObject.sortWay = "";
                $scope.sortHeadObject.predicate = "";
                $scope.sortHeadObject.reverse = false;
            }

            $scope.sortHeadObject = head;
            $scope.sortHeadObject.predicate = head['column-name'];

            if (head.sortWay == 'sort-asc') {
                $scope.sortHeadObject.reverse = true;
                head.sortWay = "sort-desc";
            } else if (head.sortWay == 'sort-desc') {
                $scope.sortHeadObject.reverse = false;
                head.sortWay = "sort-asc";
            } else {
                $scope.sortHeadObject.reverse = false;
                head.sortWay = "sort-asc";
            }

            //请求服务器
            $scope.nowPage = 1;
            reloadTableBody();
        }

        $scope.tableAddButtonClickEvent = function() {
            // var dialog = $("#addWindow").data('dialog');

            // $scope.createObject = {};
            // for (var i = 0; i < $scope.tableHead.length; i++) {
            //     $scope.createObject[$scope.tableHead[i].name] = "";
            // }
            // dialog.open();
            form.initVariable($scope, $q);
            form.defineGetFormDataUrl($scope.getSingleDataUrl);
            form.defineSaveFormDataUrl($scope.saveSingleDataUrl);
            form.initFunctions();
            form.initForm(null, "add");
        }

        //表格工具条中删除按钮点击事件
        $scope.tableDeleteButtonClickEvent = function() {
            var datas = $scope.tableData;
            var deleteIds = "";
            for (var i = 0; i < datas.length; i++) {
                if (datas[i].checked) {
                    deleteIds += datas[i].rowId + ",";
                    datas.splice(i, 1);
                    i--;
                }
            }

            deleteIds = deleteIds.substring(0, deleteIds.length - 1);
            //提交服务器删除的ids
            if (deleteIds == undefined || deleteIds.length <= 0 || deleteIds == '') {
                alert("请选中要删除的行");
                return;
            }
            var promise = myHttpHandler("DELETE", $scope.deleteDatasUrl, { ids: deleteIds });
            promise.then(function(data) {
                // alert(angular.toJson(data));
            });
        }

        $scope.addWindowSaveButtonClickEvent = function() {
            //上传修改的数据到服务器
            var promise = myHttpHandler("PUT", $scope.saveSingleDataUrl, { record: angular.toJson($scope.createObject) });
            promise.then(function(data) {
                var dialog = $("#addWindow").data('dialog');
                dialog.close();
                $scope.tableRefreshButtonClickEvent();
            });
            // alert(angular.toJson($scope.createObject));
            // var dialog = $("#addWindow").data('dialog');
            // dialog.close();   
        }

        $scope.addWindowCloseButtonClickEvent = function() {
            var dialog = $("#addWindow").data('dialog');
            dialog.close();
        }

        $scope.tableRefreshButtonClickEvent = function() {
            //重新载入表格数据
            $scope.nowPage = 1;
            $scope.isSelectAllChecked = false;
            $scope.nowSelectItem = -1;
            reloadTableBody();
        }

        //跳转到指定页面
        $scope.toPointPage = function() {
            //跳转到指定页码
            if ($scope.inputPage == undefined || $scope.inputPage <= 0) {
                $scope.inputPage = 1;
            }
            if ($scope.inputPage >= $scope.maxPageNumber) {
                $scope.inputPage = $scope.maxPageNumber;
            }
            $scope.pageButtonClickEvent($scope.inputPage);
        }

        //当在跳转输入框中按下回车时，触发跳转事件
        $scope.gotoPageByKeyPress = function(event) {
            if (event.keyCode == 13) {
                if ($scope.inputPage == undefined || $scope.inputPage <= 0) {
                    $scope.inputPage = 1;
                }
                if ($scope.inputPage >= $scope.maxPageNumber) {
                    $scope.inputPage = $scope.maxPageNumber;
                }
                $scope.pageButtonClickEvent($scope.inputPage);
            }
        }

        $scope.afterTableItemClick = function() {

        }

        $scope.beforeTableItemClick = function() {

        }

        //表格项点击事件
        $scope.tableItemClick = function(event, item) {
            $scope.beforeTableItemClick();
            $scope.nowSelectItem = item.rowId;

            var obj = event.target;

            $scope.afterTableItemClick();
        }

        $scope.rowClickEvent = function(row) {

        }

        $scope.zutable = returnData;
    }

    var afterPageButtonClick = function(func) {
        $scope.afterPageButtonClick = func;
    }

    var beforePageButtonClick = function(func) {
        $scope.beforePageButtonClick = func;
    }

    var afterTableItemClick = function(func) {
        $scope.afterTableItemClick = func;
    }

    var beforeTableItemClick = function(func) {
        $scope.beforeTableItemClick = func;
    }
    var returnData = {
        initFunctions: initFunctions,
        initVarible: initVarible,
        defineGetTableBodyUrl: defineGetTableBodyUrl,
        defineGetSingleDataUrl: defineGetSingleDataUrl,
        defineDeleteDatasUrl: defineDeleteDatasUrl,
        defineSaveSingleDataUrl: defineSaveSingleDataUrl,
        defineDeleteSingleDataUrl: defineDeleteSingleDataUrl,
        defineTableName: defineTableName,
        tableRefresh: function() {
            $scope.tableRefreshButtonClickEvent();
        },
        gotoPointPage: function(page) {
            $scope.nowPage = page;
            $scope.toPointPage();
        },
        afterPageButtonClick: afterPageButtonClick,
        beforePageButtonClick: beforePageButtonClick,
        afterTableItemClick: afterTableItemClick,
        beforeTableItemClick: beforeTableItemClick,
        getNowPage: function() {
            return $scope.nowPage;
        },
        getNowSelectItem: function() {
            return $scope.nowSelectItem;
        },
        selectItem: function(rowId) {
            $scope.nowSelectItem = rowId;
        },
        changeFilterId: function(filterid) {
            $scope.Fid = filterid;
        },
        rowClickEvent: function(fn) {
            $scope.rowClickEvent = fn;
        },
        //显示或者隐藏默认的操作按钮
        showRowOperationButton: function(show) {
            $scope.showRowOperationButton = show;
        },
        /*
            增加自定义列
            freeColumn:{
                show:false,//是否显示
                style:"width:7%;height:100%;position:xxx",//style
                content:"xxx",//列内容
                event:function(){..}//列点击事件
            }
        */
        addFreeColumn: function(freeColumn) {
            $scope.freeColumn = freeColumn;
            for (key in freeColumn.event) {
                $scope[key] = freeColumn.event[key];
            }
        },
        afterTableFreshOk: function(fn) {
            $scope.afterTableFreshOk = fn;
        }
    }
    return returnData;
});
